package com.example.demo.ctrl.config.threadTest;

/**
 * ThreadLocal测试，为什么他是线程安全的，可以发现多个线程操作ThreadLocal的值互不干扰
 * 教程：https://blog.csdn.net/X8i0Bev/article/details/101086604
 */
public class ThreadLocalTest {

    public static void main(String[] args) {
        //启动线程1
        new Thread("thread1"){
            @Override
            public void run(){
                update(this.getName());
            }

        }.start();

        //启动线程2
        new Thread("thread2"){
            @Override
            public void run(){
                update(this.getName());
            }

        }.start();

        //启动线程3
        new Thread("thread3"){
            @Override
            public void run(){
                update(this.getName());
            }

        }.start();
    }


    public static void update(String threadName){
        initialValue.set(initialValue.get()+66);
        System.out.println(threadName+"结果："+initialValue.get());
    }

    private static ThreadLocal<Integer> initialValue=new ThreadLocal<Integer>(){
        //初始化ThreadLocal的值
        @Override
        protected Integer initialValue(){
            return 10;
        }
    };
}
